<template>
	<view style="padding-bottom: 20rpx;">
		<!-- <ad  ad-theme="white" ad-unit-id="898h4rynas49ta78koID"></ad> -->
		<!-- <ad ad-unit-id="898h4rynas49ta78ko" @load="onload" @close="onclose" @error="onerror"></ad> -->
		<view class="swipers">
			<!-- 轮播图 -->
			<swiper :indicator-dots="false" class="swiper" :autoplay="true" interval="5000" duration="500"
				:circular="true">
				<swiper-item v-for="(item,index) in swiperList" :key='index' @tap="goPage(item.url)">
					<image :src="item.imageUrl" mode="aspectFill" style="width: 100%;height: 100%;"></image>
				</swiper-item>
			</swiper>
			<!-- 公告 -->
			<view class="swipers-gg flex align-center">
				<image src="../../static/images/index/ggIcon.png" mode=""></image>
				<view class="swipers-gg-txt">
					<swiper :autoplay="true" :vertical="true" :interval="4000" :circular="true" :indicator-dots="false"
						class="swipers-gg-txt-gg">
						<block v-for="(item, index) in noticeList">
							<swiper-item @tap='goMsg(item.url)'>
								<view class="swipers-gg-txt-gg-s">{{item.title}}</view>
							</swiper-item>
						</block>
					</swiper>
				</view>
			</view>
		</view>
		<!-- 搜索/金刚区 -->
		<view class="centers">
			<!-- 搜索 -->
			<view class="centers-search flex align-center justify-center">
				<view @click.stop="goSearch" class="centers-search-box flex align-center justify-center">
					<u-search bg-color="#ffffff" :show-action="false" placeholder="今日正在热播" v-model="keyword"></u-search>
				</view>
			</view>
			<!-- 金刚区 -->
			<view class="centers-cistrict flex align-center justify-center">
				<view class="centers-cistrict-box">
					<swiper :indicator-dots="true" class="centers-cistrict-boxs" :autoplay="false" :interval="3000"
						:duration="300">
						<swiper-item v-for="(item,index) in gridList" :key="index">
							<view class="swiper-item flex align-center justify-around">
								<view class="swiper-item-s" @click="goGridList(ite)" v-for="(ite,ind) in item.child"
									:key="ind">
									<view class="swiper-item-s-img">
										<image :src="ite.imageUrl" mode="aspectFill"></image>
									</view>
									<view class="swiper-item-s-txt">
										{{ite.name}}
									</view>
								</view>
								<block v-if="item.child.length == 2">
									<view class="swiper-item-s" style="height: 0;"></view>
									<view class="swiper-item-s" style="height: 0;"></view>
									<view class="swiper-item-s" style="height: 0;"></view>
								</block>
								<block v-if="item.child.length == 3">
									<view class="swiper-item-s" style="height: 0;"></view>
									<view class="swiper-item-s" style="height: 0;"></view>
								</block>
								<!-- <block v-if="item.child.length == 4">
									<view class="swiper-item-s" style="height: 0;"></view>
								</block> -->

							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</view>
		<!-- tabs -->
		<view class="tabs flex align-center justify-center">
			<view class="tabs-box flex align-center">
				<view class="tabs-box-item" @click="selectTabs(index)" :class="current == index?'tabsActive':''"
					v-for="(item,index) in tabsList" :key="index">
					{{item.name}}
					<view class="tabs-box-item-line" v-if="current == index"></view>
				</view>
			</view>
		</view>
		<!-- 视频列表 -->
		<videoList @success="posterSuccess" :list="courseList" />
		<u-loadmore v-if="courseList.length > 0" :status="status" />
		<empty v-if="courseList.length == 0" />
		<uni-popup ref="popusAuthorization" type="center" :maskClick="false">
			<view class="contentview">
				<view class="title">隐私保护指引</view>
				<view class="des" @click="openPrivacyContract">
					在使用当前小程序服务之前，请仔细阅读<text
						style="color: #5074FF;">{{privacyContractName}}</text>。如你同意{{privacyContractName}}，请点击“同意”开始使用。
				</view>
				<view class="btns">
					<button class="item reject" @click="exitMiniProgram">拒绝</button>
					<button id="agree-btn" class="item agree" open-type="agreePrivacyAuthorization"
						@agreeprivacyauthorization="handleAgreePrivacyAuthorization">同意</button>
				</view>
			</view>
		</uni-popup>
		
		<view style="margin: 10rpx auto;margin: 5px auto;position: fixed;bottom: 10%;right: 0;">
					<button
					  open-type="im"
					  :data-im-id="imId"
					  @im="imCallback"
					  @error="onimError"
					  style="
						background-color: rgb(94 97 109 / 57%);
						color: #FFFFFF;
						font-size: 12px;
						height: 60px;
						width: 75px;
						padding: 0;
						border-radius: 0;
						border-top-left-radius: 15px;
						border-bottom-left-radius: 15px;"
						
					>
					<view class="">
						<u-icon name="server-man" color="#fff" size="28"> </u-icon>
						<text style="margin: 0 5px;">客服</text>
					</view>
					
					  <text style="display: block;font-size: 9px;">9:00~22:00</text>
					</button>
			</view>
	</view>
</template>

<script>
	import empty from '../../components/empty.vue'
	import videoList from '../../components/videoList/videoList.vue'
	export default {
		components: {
			videoList,
			empty
		},
		data() {
			return {
				timeStatus:'',
				imId:'chiguakefu',
				status: 'loadmore',
				swiperList: [], //轮播图列表
				noticeList: [], //公告列表
				keyword: '',
				gridList: [], //获取金刚区类表
				current: 0, //tabs索引
				tabsList: [{
						name: '本周热门',
						id: 2,
					},
					{
						name: '本周排行榜	',
						id: 1,
					},
					{
						name: '最新热播',
						id: '',
					}
				], //tabs列表
				status: 'loadmore',
				limit: 10,
				page: 1,
				pages: 1,
				courseList: [], //视频列表
				privacyContractName: '',
				bgImg: '',
				tuiguang: '',
			};
		},
		onShareAppMessage(res) {
			return {
				path: '/pages/index/index?invitation=' + this.invitationCode, //这是为了传参   onload(data){let id=data.id;} 
				title: this.tuiguang,
				imageUrl: this.bgImg
			}
		},
		onLoad(options) {
			// this.TTlogin()
			const systemInfo = wx.getSystemInfoSync();
			uni.setStorageSync('osName',systemInfo.osName)
			// console.log(tt.canIUse('video-player.bindgetsource'),'TT')
			// console.log(tt.canIUse('video-player'),'aaaaaa')
			// ios
			//android
			// #ifdef MP-WEIXIN
			let that = this
			try {
				wx.getPrivacySetting({
					success: res => {
						console.log("是否需要授权：", res.needAuthorization, "隐私协议的名称为：", res.privacyContractName)
						if (res.needAuthorization) {
							that.privacyContractName = res.privacyContractName;
							that.$refs.popusAuthorization.open();
						}
					},
					fail: () => {},
					complete: () => {},
				})
			} catch (e) {
				//TODO handle the exception
			}
			// #endif
			this.getBgImg()
			this.invitationCode = uni.getStorageSync('invitationCode')
			// #ifdef MP-WEIXIN
			if (options.scene) { //这里为线上操作
				//此处的二维码  page/index/index?brokerId=123
				let scene = decodeURIComponent(options.scene);
				console.log('index scene: ', scene) //brokerId=123  为字符串，需要我们去分割
				uni.setStorageSync('invitation', scene)
			}

			// #endif
			if (options.invitation) {
				uni.setStorageSync('invitation', options.invitation)
			}
			//渠道来源
			if(options.channel_no){
				uni.setStorageSync('channel_no', options.channel_no)
			}
			//指定路径
			if(options.pageUrl){
				const queryParams = Object.keys(options)
				  .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(options[key])}`)
				  .join('&');
				 
				// 拼接完整的url
				const fullUrl = `${options.pageUrl}?${queryParams}`;
				 console.log(fullUrl,"fullUrl")
				// 跳转到目标页面，携带所有options
				uni.navigateTo({
				  url: fullUrl
				});
			}
		},
		onShow() {
			const interstitialAd = tt.createInterstitialAd({
			  adUnitId: "898h4rynas49ta78ko",
			});
			interstitialAd
			  .load()
			  .then(() => {
			    interstitialAd.show();
			  })
			  .catch((err) => {
			    console.log(err);
			  })
			this.estimateTime()
			let token = uni.getStorageSync('token')
			//如果有tokne并且没过期
			if(token && !this.timeStatus){
				this.getBannerList()
				this.getMsg()
				this.getGardList()
				this.getCourseList()
			}else{//剩下的情况全部执行默认登录
				this.TTlogin()
			}
		
			//#ifdef H5
			let that = this
			this.$u.get('/app/common/type/108').then(res => { //// 是否开启公众号自动登陆 108
				if (res.code == 0 && res.data) {
					if (res.data.value == '是') {
						let ua = navigator.userAgent.toLowerCase();
						if (ua.indexOf('micromessenger') !== -1) {
							let openid = uni.getStorageSync('openId');
							let userId = uni.getStorageSync('userId');
							if (userId) {
								if (!openid) {
									if (window.location.href.indexOf('?code=') !== -1 || window.location.href
										.indexOf(
											'&code=') !==
										-1) {
										let code;
										if (window.location.href.indexOf('?code=') !== -1) {
											code = window.location.href.split('?code=')[1].split('&')[0];
										} else {
											code = window.location.href.split('&code=')[1].split('&')[0];
										}
										if (userId) {
											that.$u.get('/app/user/openId/' + code + '/' + userId).then(
												res => {
													uni.setStorageSync('openId', res.data)
												});
										}
									} else {
										window.location.href =
											'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
											that.$queue.getWxAppid() +
											'&redirect_uri=' +
											window.location.href.split('#')[0] +
											'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
									}
								}
							}
						}
					}
				}
			});
			//#endif
		},
		onReachBottom() {
			if (this.page < this.pages) {
				this.page += 1
				this.status = 'loading'
				this.getCourseList()
			} else {
				this.status = 'nomore'
			}
		},
		onPullDownRefresh() {
			this.page = 1
			this.getCourseList()
		},
		methods: {
			onload(e) {
			  console.log("onload");
			},
			onclose(e) {
			  console.log("onclose: " + e.detail);
			},
			onerror(e) {
			  console.log("onerror: " + e.detail.errCode + " message:: " + e.detail.errMsg);
			},
			isAfterSpecifiedTime(specifiedTime) {  
			    const currentTime = new Date();  
			    const specifiedDate = new Date(specifiedTime);    
			    return currentTime > specifiedDate;  
			},
			estimateTime(){
				let expireDate  = uni.getStorageSync('logintime')
				if(this.isAfterSpecifiedTime(expireDate)){
					//token已过期
					this.timeStatus = true
				}else{
					this.timeStatus = false
				}
			},
			getToken(){
				let _token = uni.getStorageSync('token')
				let data = {
					token : _token
				}
			this.$Request.getT('/app/Login/checkTokenExpire', data).then(res=>{
					if(res.expired){
						this.TTlogin()
					}else{
						this.getBannerList()
						this.getMsg()
						this.getGardList()
						this.getCourseList()
					}
			})	
			},	
			TTlogin(){
				let that = this
					tt.login({
						  force: true,
						  success(res) {
							  console.log('登录')
							that.TTloginOpenid(res.code)
						  },
						  fail(res) {
							console.log(`login 调用失败`);
						  },
						});
					},
					fail(res) {
					  console.log("getUserProfile 调用失败", res);
				},
				TTloginOpenid(_code){
					let data = {
						code:_code
					}
						this.$Request.getT('/app/Login/douyinLogin', data).then(res => {
						console.log(res,'换取openid')
						
						this.getUserData(res.data.open_id)
						})
				},
				getUserData(_openId){
						this.$u.post("/app/Login/insertDouyinUser", {
							openId:_openId,
							// userName:this.userName,
							// avatar:this.avatar,
							// sex:this.sex
						}).then(res => {
							console.log(res,'登陆成功')
							uni.setStorageSync("token", res.token)
							uni.setStorageSync("userId", res.user.userId)
							uni.setStorageSync('loginStatu',false)
							uni.setStorageSync('logintime',res.expireDate)
						
							// this.$queue.setData("token", res.token);
							// this.$queue.setData("userId", res.user.userId);
							this.getBannerList()
							this.getMsg()
							this.getGardList()
							this.getCourseList()
							// uni.switchTab({
							// 	url: '/pages/index/index'
							// })
						});
				},
			imCallback(e) {
			  console.log("跳转IM客服成功", e.detail);
			},
			onimError(e) {
							  console.log(this.imId)
			  console.log("拉起IM客服失败", e.detail);
			},
			
			// 打开隐私协议页面
			openPrivacyContract() {
				let that = this;
				wx.openPrivacyContract({
					fail: () => {
						that.$queue.showToast('遇到错误无法打开！');
					}
				})
			},
			// 拒绝隐私协议
			exitMiniProgram() {
				// 直接退出小程序
				wx.exitMiniProgram()
			},
			// 同意隐私协议
			handleAgreePrivacyAuthorization() {
				this.$refs.popusAuthorization.close();
			},
			//获取背景图
			getBgImg() {
				this.$u.get('app/banner/selectBannerList?classify=5').then(res => {
					if (res.code == 0) {
						this.bgImg = res.data[0].imageUrl
						this.tuiguang = res.data[0].describes
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none'
						});
					}
				});
			},
			//点击回调
			posterSuccess(item) {
				let userId = uni.getStorageSync('userId')
				console.log(userId,'走到这里了')
				if (userId) {
					uni.navigateTo({
						url: '/me/detail/detail?id=' + item.courseId + '&courseDetailsId=' + item.courseDetailsId
					})
				} else {
					uni.navigateTo({
						url: "/pages/login/login"
					})
				}
			},
			// 获取资源列表
			getCourseList() {
				let data = {
					limit: this.limit,
					page: this.page,
					sort: this.tabsList[this.current].id,
				}
				this.$u.api.courseList(data).then(res => {
					uni.stopPullDownRefresh()
					if (res.code == 0) {
						this.pages = res.data.totalPage
						if (this.page < this.pages) {
							this.status = 'loadmore'
						} else {
							this.status = 'nomore'
						}
						if (this.page == 1) {
							this.courseList = res.data.list
						} else {
							this.courseList = [...this.courseList, ...res.data.list]
						}
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none'
						});
					}
					uni.stopPullDownRefresh();

				})
			},
			//切换类型
			selectTabs(index) {
				this.current = index
				this.page = 1

				this.getCourseList()
			},
			// 跳转资源列表
			goGridList(e) {
				console.log(uni.getStorageSync('token'),'pppppppppppppp')
				if (uni.getStorageSync('token')) {
					uni.navigateTo({
						url: e.url
					})
				} else {
					uni.navigateTo({
						url: "/pages/login/login"
					})
				}
			},
			//处理分割金刚区
			processArray(arr) {
				let arr2 = [];
				let child = [];
				for (let i = 0; i < arr.length; i++) {
					child.push(arr[i]);

					if (child.length === 5) {
						arr2.push({
							child: child
						});
						child = [];
					}
				}
				// 如果arr数组的长度不是5的倍数，将剩余的元素添加到arr2数组的最后一个child中
				if (child.length > 0) {
					arr2.push({
						child: child
					});
				}

				return arr2;
			},
			// 获取金刚区列表
			getGardList() {
				this.$u.api.bannerList({
					classify: '2',
				}).then(res => {
					if (res.code == 0) {
						let arr = []
						res.data.forEach(ret => {
							if (ret.state == 1) {
								arr.push(ret)
							}
						})
						this.gridList = this.processArray(arr)
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none'
						});
					}
				})
			},
			// 跳转搜索
			goSearch() {
				uni.navigateTo({
					url: '/pages/index/search/index'
				});
			},
			// 跳转公告链接
			goMsg(e) {
				if (url.indexOf('/pages/') !== -1 || url.indexOf('/me/') !== -1) {
					uni.navigateTo({
						url
					});
				} else {
					//#ifndef H5
					uni.navigateTo({
						url: '/pages/index/webView?url=' + url
					});
					//#endif
					//#ifdef H5
					window.location.href = url;
					//#endif	
				}
			},
			//轮播图跳转
			goPage(url) {
				let token = uni.getStorageSync('token')
				console.log(token,'-----------------')
				if (token) {
					if (url) {
						console.log(url,'1111111111111111111111111')
						if (url.indexOf('/pages/') !== -1 || url.indexOf('/me/') !== -1) {
							console.log(url,'2222222222222222222222222')
							uni.navigateTo({
								url
							});
						} else {
							//#ifndef H5
							console.log(url,'3333333333333333333333333333333333')
							uni.navigateTo({
								url: '/pages/index/webView?url=' + url
							});
							//#endif
							console.log(url,'444444444444444444444')
							//#ifdef H5
							console.log(url,'555555555555555555555555')
							window.location.href = url;
							//#endif	
							console.log(url,'66666666666666666')
						}
					}
				} else {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			// 公告
			getMsg() {
				let data = {
					page: 1,
					limit: 5,
					state: 1
				}
				this.$u.api.msg(data).then(res => {
					if (res.code == 0) {
						this.notice = res.data.list
						res.data.list.forEach(res => {
							this.noticeList.push(res)
						})
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none'
						});
					}
				})
			},
			// 获取轮播图列表
			getBannerList() {
				this.$u.api.bannerList({
					classify: '1'
				}).then(res => {
					if (res.code == 0) {
						res.data.forEach(d => {
							if (d.state == 1) {
								this.swiperList.push(d)
							}
						})

					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none'
						});
					}
				})
			},
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F7FF
	}

	.swipers {
		width: 100%;
		height: 588rpx;
		position: relative;

		.swiper {
			width: 100%;
			height: 100%;
		}

		.swipers-gg {
			position: absolute;
			width: 686rpx;
			height: 62rpx;
			background-color: rgba(255, 255, 255, 0.8);
			border-radius: 16rpx;
			bottom: 130rpx;
			left: 50%;
			transform: translate(-50%, 0);

			image {
				width: 92rpx;
				height: 52rpx;
				margin-left: 20rpx;
			}

			.swipers-gg-txt {
				width: calc(100% - 10rpx - 40rpx - 92rpx);
				height: 100%;
				margin-left: 10rpx;

				.swipers-gg-txt-gg {
					width: 100%;
					height: 100%;
				}

				.swipers-gg-txt-gg-s {
					width: 100%;
					height: 100%;
					line-height: 62rpx;
					color: #333333;
					font-size: 26rpx;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
			}
		}
	}

	.centers {
		width: 100%;
		height: auto;
		background-color: #F5F7FF;
		border-radius: 60rpx 60rpx 0 0;
		margin-top: -100rpx;
		position: relative;

		.centers-search {
			width: 100%;
			height: 92rpx;
			// margin-top: 20rpx;
			padding-top: 20rpx;

			.centers-search-box {
				width: 686rpx;
				height: 100%;
				background-color: #ffffff;
				border-radius: 46rpx;
				padding: 0 24rpx;
			}
		}

		.centers-cistrict {
			width: 100%;
			height: 216rpx;
			margin-top: 24rpx;

			.centers-cistrict-box {
				width: 686rpx;
				height: 100%;
				background-color: #ffffff;
				border-radius: 24rpx;

			}

			.centers-cistrict-boxs {
				width: 100%;
				height: 100%;

				border-radius: 24rpx;
			}

			.swiper-item {
				width: 100%;
				height: 125rpx;
				margin-top: 30rpx;
				padding: 0 20rpx;
			}

			.swiper-item-s {
				width: calc(100% / 5 - 30rpx);
				height: 100%;
			}

			.swiper-item-s-img {
				width: 84rpx;
				height: 84rpx;
				margin: 0 auto;

				image {
					width: 100%;
					height: 84rpx;
				}
			}

			.swiper-item-s-txt {
				width: 100%;
				text-align: center;
				margin-top: 10rpx;
				color: #333333;
				font-size: 26rpx;
				margin-top: 10rpx;
			}
		}
	}

	.tabs {
		width: 100%;
		height: auto;
		margin-top: 30rpx;
		margin-bottom: 30rpx;

		.tabs-box {
			width: 686rpx;
		}

		.tabs-box-item {
			color: #333333;
			font-size: 32rpx;
			margin-right: 50rpx;
			position: relative;
		}

		.tabs-box-item-line {
			width: 30rpx;
			height: 6rpx;
			background-color: #5173F8;
			position: absolute;
			left: 50%;
			top: 100%;
			transform: translate(-50%, 0);
			border-radius: 30rpx;
			margin-top: 6rpx
		}
	}

	.tabsActive {
		color: #5173F8 !important;
		font-weight: bold;
	}

	.contentview {
		width: 632rpx;
		padding: 48rpx;
		box-sizing: border-box;
		background: #fff;
		border-radius: 16rpx;
	}

	.contentview .title {
		text-align: center;
		color: #333;
		font-weight: bold;
		font-size: 32rpx;
	}

	.contentview .des {
		font-size: 26rpx;
		color: #666;
		margin-top: 40rpx;
		text-align: justify;
		line-height: 1.6;
	}

	.contentview .des .link {
		color: #5074FF;
		text-decoration: underline;
	}

	button::after {
		border: none;
	}

	.btns {
		margin-top: 48rpx;
		display: flex;
	}

	.btns .item {
		justify-content: space-between;
		width: 244rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 16rpx;
		box-sizing: border-box;
		border: none;
	}

	.btns .reject {
		background: #f4f4f5;
		color: #909399;
	}

	.btns .agree {
		background: #5074FF;
		color: #fff;
	}
</style>